﻿using System;
using System.Diagnostics;
using Reflector.CodeModel;

namespace CallGraphExtractor
{
    [DebuggerStepThrough]
    public static class ExtensionOfIType
    {
        /// <summary>
        /// Resolves the <see cref="ITypeDeclaration"/> from the <see cref="IType"/> instance.
        /// </summary>
        /// <param name="type">The instance</param>
        /// <param name="typeDeclaration">
        /// When this method returns, contains the resolved <see cref="ITypeDeclaration"/> if the <see cref="IType"/>
        /// instance is convertable to <see cref="ITypeDeclaration"/> or to <see cref="ITypeReference"/>.
        /// If the conversion is not possible, the value is null.
        /// </param>
        /// <returns>Indicates whether the method was successful</returns>
        public static bool TryGetTypeDeclaration(this IType type, out ITypeDeclaration typeDeclaration)
        {
            ITypeDeclaration td = type as ITypeDeclaration;
            typeDeclaration = null;
            if (td != null)
            {
                typeDeclaration = td;
                return true;
            }

            ITypeReference tr = type as ITypeReference;
            if (tr != null)
            {
                typeDeclaration = tr.Resolve();
                return true;
            }

            return false;

            throw new ArgumentException(
                "Az adott példány esetén nem ismert a kapcsolódó ITypeDeclaration meghatározásának módja!",
                "type");
        }

        public static bool TryGetArrayType(this IType type, out IArrayType arrayType)
        {
            arrayType = type as IArrayType;
            return arrayType != null;
        }
    }
}
